using System.Data;

namespace ETestIT.Tests
{
    using System;
    using System.Linq.Expressions;
    using System.Reflection;
    using System.Text;
    using Core;
    using ETestIT.DataAccess.Repository;

    public enum Table
    {
        Users,
        JobTitles,
        Candidats,
        Resumes,
        CandidateResumes
    }

    public class Const
    {
    }

    public static class NUnitHelperExtension
    {
        public static bool ContainsARecordWithKey(this Table tableName, Guid recordId)
        {
            return new FluentCommand<int>(string.Format("SELECT count(*) FROM {0} WHERE Id = '{1}'", tableName, recordId)).AsScalar() == 1;
        }

        public static bool ContainsDataForProperies<T>(this Table tableName, T entity, params Expression<Func<T, object>>[] expression) where T: Entity
        {
            var thePropertiesListValuePairs = new StringBuilder();

            foreach (var param in expression)
            {
                var propInfo = GetProperty(param);
                var val = propInfo.GetValue(entity, null);

                thePropertiesListValuePairs.AppendFormat("AND {0} = '{1}' ", propInfo.Name, val);
            }

            return new FluentCommand<int>(string.Format("SELECT count(*) FROM {0} WHERE Id = '{1}' {2}", 
                tableName,
                entity.Id,
                thePropertiesListValuePairs)).AsScalar() == 1;
        }

        public static PropertyInfo GetProperty<T>(Expression<Func<T, object>> expression)
        {
            MemberExpression memberExpression = null;

            if (expression.Body.NodeType == ExpressionType.Convert)
            {
                memberExpression = ((UnaryExpression)expression.Body).Operand as MemberExpression;
            }
            else if (expression.Body.NodeType == ExpressionType.MemberAccess)
            {
                memberExpression = expression.Body as MemberExpression;
            }

            if (memberExpression == null)
            {
                throw new ArgumentException("Not a member access", "expression");
            }

            return memberExpression.Member as PropertyInfo;
        }

    }

}